<template>
  <div class="boundhouse">
    <div class="bg">
      <van-nav-bar title="绑定房屋" left-arrow @click-left="$router.go(-1)" fixed/>

      <span class="nav-bar">房屋信息</span>

      <div class="house-info">
        <van-cell
          title="街道"
          is-link
          :value="form.streetName"
          @click="showStreetPicker = true"
        />
        <van-cell
          title="社区"
          is-link
          :value="form.communFullName"
          @click="selectCommunity"
        />

        <van-cell
          title="楼栋房号"
          is-link
          :value="form.communRoomName"
          @click="selectRoom"
        />
        <van-cell
          title="住户类型"
          is-link
          :value="form.ownerType"
          @click="showResidentPicker = true"
        />
      </div>

      <span class="nav-bar">个人信息</span>

      <div class="person-info">
        <van-field
          v-model="form.name"
          label="真实姓名"
          placeholder
          clearable
          maxlength="10"
          class="repair_input_box"
        />
        <div class="image_box">
          <div class="content_desc">人脸照片</div>
          <van-uploader
            v-model="form.avatar"
            :max-count="1"
            class="img_upload_box"
            :after-read="afterRead"
            :before-read="beforeRead"
          />
        </div>
      </div>
    </div>

    <!-- <div class="submit-box apply_btn">
      <van-button :disabled="isSubmit" @click="submit"
        >提交信息</van-button
      >
    </div> -->
    <van-button
      :disabled="!isSubmit"
      class="next_btn apply_btn"
      type="danger"
      @click="submit()"
      >提交信息</van-button
    >

    <!-- 所在街道选择 -->
    <van-popup v-model="showStreetPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="streetColumns"
        @cancel="showStreetPicker = false"
        @confirm="confirmSelectStreet"
      />
    </van-popup>
    <!-- 所在社区选择 -->
    <van-popup v-model="showCommunPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        @cancel="showCommunPicker = false"
        @confirm="confirmSelectComunity"
      />
    </van-popup>

    <!-- 楼栋房号选择 -->
    <van-popup v-model="showRoomPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="roomColumns"
        @cancel="showRoomPicker = false"
        @confirm="confirmSelectRoom"
      />
    </van-popup>

    <!-- 住户类型选择 -->
    <van-popup v-model="showResidentPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="residentData"
        @cancel="showResidentPicker = false"
        @confirm="confirmSelectType"
      />
    </van-popup>
    <van-popup v-model="showLoading">
      <van-loading color="#DC4630" />
    </van-popup>
  </div>
</template>

<script>
import houseService from "@/controller/myhouse.js";
import uploadService from "@/controller/mine.js";
import constant from "@/controller/constant.js";
import bus from "@/utils/eventBus"

export default {
  data() {
    return {
      showLoading: false,
      columns: [],
      streetColumns: [],
      neighborhoodId: "",
      form: {
        streetName: "",
        streetId: "",
        communFullName: "",
        communityId: "",
        communRoomName: "",
        roomId: "",
        ownerType: "",
        ownerTypeId: "",
        name: "",
        avatar: [],
        faceImgUrl: ""
      },
      roomColumns: [],
      showPicker: false,
      showCommunPicker: false,
      showStreetPicker: false,
      showRoomPicker: false,
      showResidentPicker: false,
      residentData: []
    };
  },
  computed: {
    // 是否激活提交按钮
    isSubmit: function() {
      return (
        this.form.streetName !== "" &&
        this.form.communFullName !== "" &&
        this.form.communRoomName !== "" &&
        this.form.name !== "" &&
        this.form.avatar.length > 0 &&
        this.form.ownerType !== ""
      );
    }
  },
  activated() {
    if (!this.$route.meta.isBack) {
      this.form = {
        streetName: "",
        streetId: "",
        communFullName: "",
        communityId: "",
        communRoomName: "",
        roomId: "",
        ownerType: "",
        ownerTypeId: "",
        name: "",
        avatar: [],
        faceImgUrl: ""
      }
      this.columns = []
      this.streetColumns = []
      this.roomColumns = []
      this.residentData = constant.ownerTypeList;
      this.neighborhoodId = JSON.parse(localStorage.getItem("userInfo")).shequId;
      this.showLoading = true
      this.getStreetList()
    }
    this.$route.meta.isBack = false;
  },
  beforeRouteEnter(to, from, next) {
    if (from.name == "houseList") {
      to.meta.keepAlive = true;
      to.meta.isBack = true;
    }
    next();
  },
  mounted() {
    bus.$on('selectHouse', data => {
      this.form.communRoomName = data.houseCode;
      this.form.roomId = data.id;
    })
    this.residentData = constant.ownerTypeList;
    this.neighborhoodId = JSON.parse(localStorage.getItem("userInfo")).shequId;
    this.showLoading = true
    this.getStreetList()
  },
  methods: {
    getStreetList() {
      houseService.community_community_get_all().then(res => {
        this.showLoading = false
        this.streetColumns = [];
        if (res.code === "0") {
          if (res.datas.length === 0) {
            this.$toast("当前暂无街道，请稍后重试");
          }
          res.datas.forEach(e => {
            this.streetColumns.push({
              text: e.communityName,
              value: e.id
            });
          });
        } else {
          if (res && res.msg) {
            this.$toast(res.msg);
          } else {
            this.$toast(constant.unusualMsg);
          }
        }
      }).catch(() => {
        this.showLoading = false
      })
    },
    getComunityList(id) {
      houseService.community_neighborhood_region(id).then(res => {
        this.showLoading = false
        this.columns = [];
        if (res.code === "0") {
          if (res.datas.length === 0) {
            this.$toast("当前暂无社区，请稍后重试");
          }
          res.datas.forEach(e => {
            this.columns.push({
              text: e.name,
              value: e.id
            });
          });
        } else {
          if (res && res.msg) {
            this.$toast(res.msg);
          } else {
            this.$toast(constant.unusualMsg);
          }
        }
      }).catch(() => {
        this.showLoading = false
      })
    },
    getComunityBuildingList(id) {
      houseService.community_house_neighborhood(id).then(res => {
        this.showLoading = false
        this.roomColumns = [];
        if (res.code === "0") {
          res.datas.forEach(e => {
            this.roomColumns.push({
              text: e.houseCode ? e.houseCode : "暂无",
              value: e.id
            });
          });
        } else {
          if (res && res.msg) {
            this.$toast(res.msg);
          } else {
            this.$toast(constant.unusualMsg);
          }
        }
      }).catch(() => {
        this.showLoading = false
      })
    },
    confirmSelectStreet(val) {
      this.showLoading = true
      this.getComunityList(val.value);
      this.form.streetName = val.text;
      this.form.streetId = val.value;
      this.form.communFullName = '';
      this.form.communityId = '';
      this.form.communRoomName = '';
      this.form.roomId = '';
      this.showStreetPicker = false;
    },
    confirmSelectComunity(val) {
      // this.showLoading = true
      // this.getComunityBuildingList(val.value);
      this.form.communFullName = val.text;
      this.form.communityId = val.value;
      this.form.communRoomName = '';
      this.form.roomId = '';
      this.showCommunPicker = false;
    },
    confirmSelectRoom(val) {
      this.form.communRoomName = val.text;
      this.form.roomId = val.value;
      this.showRoomPicker = false;
    },
    confirmSelectType(val) {
      this.form.ownerType = val.text;
      this.form.ownerTypeId = val.value;
      this.showResidentPicker = false;
    },
    selectCommunity() {
      if (!this.form.streetName) {
        this.$toast("请先选择街道！");
        return;
      }
      this.showCommunPicker = true;
    },
    selectRoom() {
      if (!this.form.communFullName) {
        this.$toast("请先选择社区！");
        return;
      }
      // this.showRoomPicker = true;
      this.$router.push({name: 'houseList', query: {id: this.form.communityId}})
    },
    beforeRead(file) {
      const acceptImgs = ['image/jpeg','image/png','image/jpg']
      if (!acceptImgs.includes(file.type)) {
        this.$toast('请上传JPG或者PNG格式的图片!')
        return false
      }
      this.showLoading = true
      return true
    },
    afterRead(file) {
      let formData = new FormData();
      formData.append("file", file.file);
      uploadService.upload_image(formData).then(res => {
        this.showLoading = false
        if (res.data.code === "0") {
          this.$toast("人脸照片上传成功！");
          this.form.faceImgUrl = res.data.datas;
        } else {
          this.form.avatar = []
          if (res && res.data && res.data.msg) {
            this.$toast(res.data.msg);
          } else {
            this.$toast(constant.unusualMsg);
          }
        }
      }).catch(() => {
        this.form.avatar = []
        this.showLoading = false
      })
    },
    submit() {
      this.showLoading = true
      const data = {
        houseId: this.form.roomId,
        userId: JSON.parse(localStorage.getItem("userInfo")).currentUser.id,
        realName: this.form.name,
        relation: this.form.ownerTypeId,
        faceImage: this.form.faceImgUrl
      };
      houseService.community_user_house_bind(data).then(res => {
        this.showLoading = false
        if (res.code === "0") {
          this.$toast("新增房屋成功！");
          this.$router.go(-1);
        } else {
          if (res && res.msg) {
            this.$toast(res.msg);
          } else {
            this.$toast(constant.unusualMsg);
          }
        }
      }).catch(() => {
        this.showLoading = false
      })
    }
  }
};
</script>
<style lang="scss">
.boundhouse {
  .image_box {
    .van-uploader__preview-image {
      width: 107px;
      height: 82px;

      .van-image__error,
      .van-image__img,
      .van-image__loading {
        border-radius: 5px;
      }
    }

    .van-uploader__upload {
      width: 107px;
      height: 82px;
      border-radius: 5px;
      border-style: solid;
      background-color: #f5f7fa;
    }

    .van-uploader__upload-icon {
      font-size: 25px;
    }
  }
}
</style>
<style lang="scss" scope>
@import "../../workstation/styles/workstation.scss";
.boundhouse {
  width: 100%;
  height: 100%;
  // position: fixed;
  background: #f5f7fa;
  // margin: -46px 0 0;

  .image_box {
    padding: 10px 0;
    border-bottom: 1px solid rgba(226, 226, 226, 0.5);

    .content_desc {
      line-height: 20px;
      font-size: 14px;
      color: #333333;
      width: 230px;
      word-break: break-all;
      float: left;
    }

    .img_upload_box {
      float: right;
    }
  }

  .image_box::after {
    content: "\20";
    display: block;
    height: 0;
    clear: both;
  }

  /deep/ .van-button {
    margin: 0.4rem;
    border-radius: 0.58667rem;
  }

  .bg {
    background: #fff;

    .house-info,
    .person-info {
      padding: 0 15px;
    }

    .van-nav-bar {
      .van-nav-bar__title {
        font-size: 18px;
        color: #333333;
        letter-spacing: 0;
        text-align: center;
      }

      .van-nav-bar__left {
        left: 15.5px;

        .van-icon-arrow-left {
          color: #333;
          font-weight: 700;
        }
      }
    }

    .nav-bar {
      text-align: left;
      padding-left: 15px;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      display: inline-block;
      margin: 25px 0 15px 0;
    }

    .van-cell {
      text-align: left;
      border-bottom: 1px solid #edeff2;
      padding: 15px 0;

      span {
        font-size: 14px;
        color: #333;
      }

      &:not(:last-child)::after {
        border-bottom: none;
      }
    }

    .person-info {
      .van-cell:nth-child(2) {
        border-bottom: none;
      }

      .repair_input_box {
        .van-field__control {
          text-align: right;
          margin-right: 15px;
        }
      }
    }
  }

  // .submit-box {
  //   .van-button {
  //     width: calc(100% - 30px);
  //     height: 44px;
  //     line-height: 44px;
  //     border-radius: 44px;
  //     // margin-top: 89px;
  //     margin-left: 15px;

  //     .van-button__text {
  //       color: #fff;
  //       font-size: 16px;
  //     }
  //   }
  // }
}
</style>
